<template>
	<div class="edu-page-warp">
		<inner-breadcrumb v-model="pathKey" :path="path" v-show="pathKey!='main'"></inner-breadcrumb>
		<template v-if="pathKey=='main'">
			<el-card shadow="never">
				<div
					class="edu-page-title"
					style="margin-bottom: 16px"
				>{{$t('course.publicElectiveCourseManange')}}</div>
				<div class="edu-opertion-bar" style="float:right;margin-bottom: 16px" v-if="underGraduate">
					<div>
						<el-button type="danger" @click="batchDelete">{{$t("message.delete")}}</el-button>
						<el-button type="primary" @click="showAddDialog">{{$t("message.add")}}</el-button>
					</div>
				</div>
				<div>
					<edu-table
						:data="courseCategories"
						@selection-change="choose"
						:total="queryForm.total_"
						:pageSize="queryForm.pageSize_"
						:current-page="queryForm.pageNum_"
						@page-change="handleCurrentChange"
					>
						<edu-table-column prop="name" :label="$t('message.name')">
							<template slot-scope="props">{{props.row.name}}</template>
						</edu-table-column>
						<edu-table-column :label="$t('label.trainingLevel')">
							<template slot-scope="props">{{props.row.trainingLevelI18n}}</template>
						</edu-table-column>
						<edu-table-column :label="$t('course.startGrade')">
							<template slot-scope="props">{{props.row.startGrade}}</template>
						</edu-table-column>
						<edu-table-column :label="$t('course.endGrade')">
							<template slot-scope="props">{{props.row.endGrade}}</template>
						</edu-table-column>
						<edu-table-column :label="$t('message.operating')">
							<template slot-scope="scope">
								<el-button
									type="text"
									@click="showChildrenDialog(scope.row)"
									size="mini"
								>{{$t('shortTermApprove.check')}}</el-button>
								<el-button type="text" size="mini" @click="showEditDialog(scope.row)">{{$t("message.edit")}}</el-button>
								<el-button
									type="text"
									size="mini"
									@click="deleteCategory(scope.row)"
								>{{$t("message.delete")}}</el-button>
							</template>
						</edu-table-column>
					</edu-table>
				</div>
			</el-card>

			<!--添加/编辑分类对话框-->
			<el-dialog
				:title="title"
				:visible.sync="courseCategoryDialog"
				width="60%"
				:close-on-click-modal="false"
				v-drag-dialog
			>
				<el-form
					:model="postForm"
					ref="postForm"
					label-position="right"
					label-width="100px"
					:rules="rules"
					label-suffix=":"
				>
					<el-row :gutter="24">
						<el-col :span="12">
							<el-form-item :label="$t('message.name')" prop="name">
								<el-input v-model="postForm.name" :placeholder="$t('message.plsInputName')" maxlength="20"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="$t('label.trainingLevel')" prop="trainingLevel">
								<el-select v-model="postForm.trainingLevel" style="width: 100%;">
									<el-option
										v-for="item in options.trainingLevel"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="24">
						<el-col :span="12">
							<el-form-item :label="$t('course.startGrade')" prop="startGrade">
								<el-date-picker
									style="width:100%"
									v-model="postForm.startGrade"
									type="year"
									:placeholder="$t('course.selectStartGrade')"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="$t('course.endGrade')" prop="endGrade">
								<el-date-picker
									style="width:100%"
									v-model="postForm.endGrade"
									type="year"
									:placeholder="$t('course.selectEndGrade')"
								></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="24">
						<el-col :span="24">
							<el-form-item class="float-right no-bottom no-right">
								<el-button @click="cancel">{{$t("message.cancel")}}</el-button>
								<el-button type="primary" @click="onSubmit">{{$t("message.save")}}</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-dialog>
		</template>

		<PublicCourseComponent
			v-show="pathKey=='courseCategory'"
			:optionCategories="optionCategories"
			:categoryTittle="categoryTittle"
			@back="pathKey='main'"
			@courseMaintenance="showCourseManage"
			ref="courseCategoryBread"
		></PublicCourseComponent>

		<CourseMaintenanceComponent
			v-show="pathKey=='maintenance'"
			:heardTitle="heardTitle"
			:options="options"
			@back="maintenanceBack"
			@addCourseBread="addCourseBread"
			ref="courseMaintenance"
		></CourseMaintenanceComponent>
		<!-- 
    	@back="pathKey='courseCategory'"
		-->
		<AddCourseComponent
			v-show="pathKey=='add'"
			:heardTitle="heardTitle"
			:options="options"
			@back="addBack"
			ref="addCourse"
		></AddCourseComponent>
	</div>
</template>
<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import {
	addcoursesCategory,
	coursesCategoryList,
	deleteCoursesCategory,
	getCoursesCategoryById,
	updateCoursesCategory,
	getChildrenNodeCoursesCategory
} from "common/src/api/resource/publicCourse";
import PublicCourseComponent from "./component/PublicCourseComponent";
import CourseMaintenanceComponent from "./component/CourseMaintenanceComponent";
import AddCourseComponent from "./component/AddCourseComponent";

export default {
	name: "publicCourse",
	components: {
		PublicCourseComponent,
		CourseMaintenanceComponent,
		AddCourseComponent
	},
	data() {
		return {
			pathKey: "main",
			path: {
				label: this.$t("courses.courseManagement"),
				key: "belong",
				disable: true,
				children: [
					{
						label: this.$t("courses.publicCourse"),
						key: "main",
						children: [
							{
								label:
									this.$t("courses.courseCategory") +
									"公共选修课442",
								key: "courseCategory",
								children: [
									{
										label: this.$t("courses.maintenance"),
										key: "maintenance",
										children: [
											{
												label: this.$t(
													"courses.addCourse"
												),
												key: "add"
											}
										]
									}
								]
							}
						]
					}
				]
			},
			heardTitle: "",
			queryForm: {
				type: 1,
				pageNum_: 1,
				pageSize_: 20,
				total_: 0
			},
			postForm: {
				name: "",
				nameEn: "",
				startGrade: "",
				endGrade: "",
				type: "1",
				remark: "",
				remarkEn: "",
				trainingLevel: ""
			},
			coursesForm: {
				pageNum_: 1,
				pageSize_: 20,
				categoryId: "",
				// term: "",
				tag: "",
				type: 1,
				trainingLevel: "",
				faculty: "",
				condition: "",
				total: 0
			},
			category: {
				pageNum_: 1,
				pageSize_: 20,
				total_: 0
			},
			options: {
				trainingLevel: [],
				startGrade: [],
				endGrade: [],
				courseCategories: [],
				courseLabel: [],
				college: [],
				term: []
			},
			rules: {
				name: [
					{
						required: true,
						message: this.$t("courses.courseCateRequire"),
						trigger: "blur"
					}
				],
				trainingLevel: [
					{
						required: true,
						message: this.$t("courses.trainingLevelRequire"),
						trigger: "blur"
					}
				],
				startGrade: [
					{
						required: true,
						message: this.$t("courses.beginGradeRequire"),
						trigger: "blur"
					}
				],
				endGrade: [
					{ validator: this.endGradeValidate, trigger: "blur" }
				]
			},

			courseCategoryDialog: false,
			courseCategories: [],
			chooseCourseCategories: [],
			editCategoryId: "",
			categoryTittle: "",
			underGraduate: true
		};
	},
	mounted: function() {
		let user =
			this.$store.state.session.user ||
			JSON.parse(localStorage.getItem("user"));
		if (user) {
			this.underGraduate = user.currentManageDptId === "1";
		}
		if (this.underGraduate) {
			this.init();
		}
	},
	methods: {
		init() {
			let now = new Date().getFullYear();
			for (let i = now - 10; i < now + 20; i++) {
				let option = { label: i, value: i };
				this.options.startGrade.push(option);
				this.options.endGrade.push(option);
			}
			let data = {
				lang: this.$store.getters.language || "cn",
				type: "allChild",
				keys: ["X_PYCC", "X_KCBQ", "X_YX"]
			};
			queryDic(data).then(res => {
				if (res.code == 200) {
					UTILS.fillSelect(
						{
							trainingLevel: "X_PYCC",
							courseLabel: "X_KCBQ",
							college: "X_YX"
						},
						res.data,
						this.options
					);
					this.options.trainingLevel = this.options.trainingLevel.filter(
						obj => obj.value != 4 && obj.value != 6
					); //过滤研究生和博士
				}
			});
			//获取子分类的课程类别
			getChildrenNodeCoursesCategory().then(res => {
				if (res.code == 200) {
					this.options.courseCategories = res.data.map(c => {
						return {
							label: c.label,
							value: c.id
						};
					});
				}

				this.optionCategories = this.options.courseCategories;
			});
			for (let i = 1; i <= 14; i++) {
				this.options.term.push({
					label: this.$t("courses.the") + i + this.$t("courses.term"),
					value: i
				});
			}
			this.getDataList();
		},
		onSubmit() {
			this.$refs.postForm.validate(valid => {
				if (!valid) {
					return;
				}
				let fn = addcoursesCategory;
				let data = _.cloneDeep(this.postForm);
				data.startGrade = this.postForm.startGrade.getFullYear();
				if (this.postForm.endGrade) {
					data.endGrade = this.postForm.endGrade.getFullYear();
				}
				if (this.editCategoryId) {
					fn = updateCoursesCategory;
					data.id = this.editCategoryId;
				}
				fn(data).then(res => {
					if (res.code == 200) {
						this.$message({
							type: "success",
							message: this.$t("common.tips.opSuccess")
						});
						this.courseCategoryDialog = false;
						this.getDataList();
					}
				});
			});
		},
		cancel() {
			this.courseCategoryDialog = false;
		},
		getDataList() {
			coursesCategoryList(this.queryForm).then(res => {
				if (res.code == 200) {
					this.courseCategories = res.data.list;
					this.queryForm.total_ = res.data.total_;
				}
			});
		},
		handleCurrentChange(val) {
			this.queryForm.pageSize_ = val.pageSize;
			this.queryForm.pageNum_ = val.pageNum;
			this.getDataList();
		},

		choose(val) {
			this.chooseCourseCategories = val;
		},
		resetInitFields() {
			this.postForm.name = "";
			this.postForm.startGrade = "";
			this.postForm.endGrade = "";
			this.postForm.trainingLevel = "";
			if (this.$refs.postForm) this.$refs.postForm.resetFields();
			this.courseCategoryDialog = true;
		},
		showAddDialog() {
			this.title = this.$t("courses.addCourseCategory");
			this.title = "新增课程类别";
			this.resetInitFields();
		},
		showEditDialog(row) {
			this.editCategoryId = row.id;
			this.title = this.$t("courses.eidtCourseCategory");
			this.resetInitFields();
			getCoursesCategoryById(row.id).then(res => {
				if (res.code == 200) {
					this.postForm.name = res.data.name;
					let startGrade = new Date();
					startGrade.setFullYear(res.data.startGrade, 1, 1);
					this.postForm.startGrade = startGrade;
					if (res.data.endGrade) {
						let endGrade = new Date();
						endGrade.setFullYear(res.data.endGrade, 1, 1);
						this.postForm.endGrade = endGrade;
					}
					this.postForm.trainingLevel = res.data.trainingLevel;
				}
			});
		},
		deleteCategory(row) {
			// this.$confirm(
			// 	this.$t("message.deleteConfirm"),
			// 	this.$t("message.confirm"),
			// 	{
			// 		confirmButtonText: this.$t("message.confirm"),
			// 		cancelButtonText: this.$t("message.cancel"),
			// 		type: "warning"
			// 	}
			this.$delConfirm().then(() => {
				deleteCoursesCategory({ ids: [row.id] }).then(res => {
					if (res.code == 200) {
						this.$message({
							type: "success",
							message: this.$t("common.tips.opSuccess")
						});
						this.getDataList();
					}
				});
			});
		},
		//批量删除
		batchDelete() {
			if (this.chooseCourseCategories.length == 0) {
				 this.$noSelectAlert();
				// this.$message({
				// 	type: "info",
				// 	message: this.$t("courses.plsChooseCourseCategories")
				// });
				return;
			}
			// this.$confirm(
			// 	this.$t("message.deleteConfirm"),
			// 	this.$t("message.confirm"),
			// 	{
			// 		confirmButtonText: this.$t("message.confirm"),
			// 		cancelButtonText: this.$t("message.cancel"),
			// 		type: "warning"
			// 	}
			this.$delConfirm().then(() => {
				deleteCoursesCategory({
					ids: this.chooseCourseCategories.map(c => c.id)
				}).then(res => {
					if (res.code == 200) {
						this.$message({
							type: "success",
							message: this.$t("common.tips.opSuccess")
						});
						this.getDataList();
					}
				});
			});
		},
		//结束年级验证
		endGradeValidate(rule, value, callback) {
			if (this.postForm.endGrade) {
				let startGrade = this.postForm.startGrade.getFullYear();
				let endGrade = this.postForm.endGrade.getFullYear();
				if (startGrade > endGrade) {
					callback(new Error(this.$t("courses.timeRequire")));
				} else {
					callback();
				}
			} else {
				callback();
			}
		},

		maintenanceBack(type) {
			this.pathKey = "courseCategory";
		},

		addBack(type) {
			this.pathKey = "maintenance";
		},

		//显示子类别对话框
		showChildrenDialog(row) {
			/* 	 this.$t("courseSummary.label") + ":" + row.name; */
			// this.childrenDialog = true;
			//	if (row) {
			this.path.children[0].children[0].label =
				this.$t("courseSummary.label") + ":" + row.name;
			this.categoryTittle =
				this.$t("courseSummary.label") + ":" + row.name;
			this.pathKey = "courseCategory";
			this.$refs["courseCategoryBread"].getChildrenCategories(row.id);
			// } else {
			// 	this.$refs["courseCategoryBread"].getChildrenCategories();
			// }

			//this.heardTitle = this.$t("courseSummary.label") + ":" + row.name;
			// this.currentCourseCategory = row;

			// this.getChildrenCategories();
		},

		//显示课程维护
		showCourseManage(row) {
			this.pathKey = "maintenance";
			this.heardTitle = this.$t("courses.maintenance");
			//if (row) {
			this.$refs["courseMaintenance"].getCoursesMaintain(row.id);
			// } else {
			// 	this.$refs["courseMaintenance"].getCoursesMaintain();
			// }
		},
		addCourseBread(categoryId) {
			this.pathKey = "add";
			this.heardTitle = this.$t("courses.addCourse");
			this.$refs["addCourse"].getCoursesByCondition(categoryId);
		}
	},
	watch: {
		pathKey(val, oldVal) {
			if (val == "main") {
				this.getDataList();
			}
			if (val == "courseCategory" && oldVal != "main") {
				this.$refs["courseCategoryBread"].getChildrenCategories();
			}
			if (val == "maintenance" && oldVal != "courseCategory") {
				this.heardTitle = "课程维护";
				this.$refs["courseMaintenance"].getCoursesMaintain();
			}
			if (val == "add" && oldVal != "maintenance") {
				this.addCourseBread();
			}
		}
	}
};
</script>
<style lang="scss" scoped>
.sub-title {
	font-size: 18px;
	margin-bottom: 10px;
}
.mycell {
	& div {
		float: left;
		margin-right: 5px;
	}
}
</style>
